﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Devtm.Parsing
{

    public class ItemEvaluateFormula : ItemFormula
    {

        protected override string VisitText(Lexer l, Context c, string value)
        {

            string result = value;
            string k = l.Value;
            ItemFormula f;

            //f = new ItemFormula();
            //var res1 = f.Parse(l, c, value);
            //c.Visitor.VisitFunction(this as Item, l.Value, );


            switch (k)
            {

                case "path":
                    f = new ItemPathFormula();
                    var res1 = f.Parse(l, c, string.Empty);
                    result += new System.IO.FileInfo(res1).DirectoryName;
                    break;

                case "name":
                    f = new ItemPathFormula();
                    var res4 = f.Parse(l, c, string.Empty);
                    result += System.IO.Path.GetFileNameWithoutExtension(new System.IO.FileInfo(res4).Name);
                    break;

                case "filename":
                    f = new ItemPathFormula();
                    var res5 = f.Parse(l, c, string.Empty);
                    result += new System.IO.FileInfo(res5).Name;
                    break;

                case "prj":
                    f = new ItemProjectFormula();
                    result += f.Parse(l, c, string.Empty);
                    break;

                case "value":
                    f = new ItemValueFormula();
                    var res2 = f.Parse(l, c, string.Empty);
                    XName x = res2.ToName();
                    var attr = c.Datas.Attribute(x);
                    if (attr == null)
                        throw new MissingFieldException(string.Format("missing attribute namespace:\"{0}\" name:\"{1}\" in the data.", x.Namespace, x.LocalName));
                    result += attr.Value;
                    break;

                case "$":
                    f = new ItemFormula();
                    var res3 = "__" + f.Parse(l, c, string.Empty);
                    if (c.Cache.ContainsKey(res3))
                        result += (c.Cache[res3] as Stack<string>).Peek();
                    break;

                default:

                    if (c.Cache.ContainsKey(k))
                    {
                        f = new ItemDataFormula() { Namespace = c.Cache[k] };
                        result = f.Parse(l, c, result);
                    }
                    else
                        throw new FormatException(k);

                    break;
            }


            return result;

        }

    }

}
